/*
 * @Description: //TODO
 * @Author: iamsmiling
 * @Date: 2021-07-11 17:30:47
 * @LastEditTime: 2021-07-12 19:37:06
 */
const router = require('koa-router')()
const { ErrorResponse, SuccessResponse } = require('../../base/base_response')
const Model = require('../../db/models/chimera_log')
const { Op } = require("sequelize");
// const {Model} = require('sequelize')

router.prefix('/log')

router.post("/add", async (ctx) => {
    let map = ctx.request.body;
    let response;
    await Model.create({
        content: map["content"]
    }).then((_) => {
        response = new SuccessResponse(map)

    }).catch((err) => {
        response = new ErrorResponse(-1, "添加日志失败")
        console.log("some thing wrong when insert a log to the table", err)
    }).finally(() => {
        ctx.body = response.toJson()
    })
})

router.get("/add", async (ctx) => {
    let map = ctx.query;
    let response;
    await Model.create({
        content: map["content"]
    }).then((_) => {
        response = new SuccessResponse(map)

    }).catch((err) => {
        response = new ErrorResponse(-1, "添加日志失败")
        console.log("some thing wrong when insert a log to the table", err)
    }).finally(() => {
        ctx.body = response.toJson()
    })
})

router.post("/delete", async (ctx) => {
    let list = ctx.request.body.id;
    let response;
    await Model.update({
        deleted: true
    }, {
        where: {
          id:{
            [Op.in]:list
          }
        }
    }).then((_) => {
        response = new SuccessResponse(list)
    }).catch((err) => {
        response = new ErrorResponse(-1, "删除失败")
        console.log("some thing wrong when delete a log from the table", err)
    }).finally(() => {
        ctx.body = response.toJson()
    })
})

router.get("/query", async (ctx) => {
    let map = ctx.query;
    let page = +(map.page ? map.page : 1);
    let page_size = +(map.page_size ? map.page_size : 10);
    let response;
    let len=0;
   await Model.findAll({
       where:{
           deleted:false
       }
   }).then((val)=>{
    len = val.length;
   }).catch(err=>{
    console.log(err)
   });
   await Model.findAll({
        limit: page_size,
        offset: (page-1)*page_size,
        where: {
            deleted: false
        }
    }).then((val)=>{
        let data = Array.isArray(val)?val.map((e)=>e.dataValues):[];
        response = new SuccessResponse({
            list:data,
            total_count:len
        })
    }).catch((err)=>{
        response = new ErrorResponse(-1, "查找失败")
        console.log(err)
    }).finally(()=>{
        ctx.body = response.toJson()
    })
   
})
module.exports = router